<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Realtime communication with WebRTC</title>
  </head>

  <body>
    <h1>Realtime communication with WebRTC</h1>
    <button id="startBtn">Start</button>
    <br />
    <video autoplay playsinline></video>
  </body>
  <script>
    const localVideo = document.querySelector("video");

    function gotLocalMediaStream(mediaStream) {
      localVideo.srcObject = mediaStream;
    }

    function handleLocalMediaStreamError(error) {
      // navigator.getUserMedia error:  NotAllowedError: Permission denied
      console.log("navigator.getUserMedia error: ", error);
    }

    // https://w3c.github.io/mediacapture-main/getusermedia.html#mediastreamconstraints
    // https://w3c.github.io/mediacapture-main/getusermedia.html#dom-mediatrackconstraintset
    const mediaStreamConstraints = {
      video: {
        // 宽度最小是 640，理想的宽度是 1280
        width: { min: 640, ideal: 1280 },
        // 高度最小是 360，最理想高度是 720
        height: { min: 360, ideal: 720 },
        // double : 视频的帧率最小 20 帧每秒
        frameRate: { min: 20 },
        // double : 宽高比是 16:9
        aspectRatio: 16 / 9,
        // DOMString : user : 前置摄像头, environment : 后置摄像头, left : 前置左侧摄像头, right : 前置右侧摄像头
        // https://w3c.github.io/mediacapture-main/getusermedia.html#dom-videofacingmodeenum
        // facingMode: "user",
        // 是否允许调整图像大小
        // DOMString : "none", "crop-and-scale"
        // https://w3c.github.io/mediacapture-main/getusermedia.html#dom-videoresizemodeenum
        // resizeMode: "none",
        // boolean
        // backgroundBlur: true,
        // DOMString : 设备 ID
        // deviceId :
        // DOMString : 设置组 ID
        // groupId,
      },
      audio: {
        // 音频采样率
        // sampleRate: 8000,
        // 音频采样大小（精度）
        sampleSize: 16,
        // 开启回音消除
        echoCancellation: true,
        // 开启降噪
        noiseSuppression: true,
        // 开启自动增益功能
        autoGainControl: true,
        // double : 延迟大小
        latency: 1,
        // 声道数
        channelCount: 2,
        // 延迟大小
        latency: 1,
      },
    };

    const startBtn = document.getElementById("startBtn");
    startBtn.onclick = function () {
      startBtn.disabled = true;
      // 可以通过 Promise 获得 MediaStream 对象
      var promise = navigator.mediaDevices.getUserMedia(mediaStreamConstraints);
      promise.then(gotLocalMediaStream).catch(handleLocalMediaStreamError);
    };
  </script>
</html>
